package threecreateways;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

// 多线程同步下载图片方式三
public class PictureDownDemo3 implements Callable<Boolean> {
    private String url;
    private String name;

    public PictureDownDemo3(String url, String name) {
        this.url = url;
        this.name = name;
    }
    public Boolean call() throws Exception {
        WebDownloader2 webDownloader = new WebDownloader2();
        webDownloader.downloader(url,name);
        System.out.println("下载了网络文件："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        PictureDownDemo3 thread1 = new PictureDownDemo3("https://tse1-mm.cn.bing.net/th/id/OIP-C.7KW5GT7NQ8yUGlBbCHEm0gHaNK?pid=ImgDet&rs=1", "文件1");
        PictureDownDemo3 thread2 = new PictureDownDemo3("https://ts1.cn.mm.bing.net/th/id/R-C.df4462fabf18edd07195679a5f8a37e5?rik=FnNvr9jWWjHCVQ&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50059%2f8720.jpg_wh1200.jpg&ehk=ofb4q76uCls2S07aIlc8%2bab3H5zwrmj%2bhqiZ%2fyw3Ghw%3d&risl=&pid=ImgRaw&r=0", "文件2");
        PictureDownDemo3 thread3 = new PictureDownDemo3("https://desk-fd.zol-img.com.cn/t_s960x600c5/g5/M00/0A/0B/ChMkJl4X3nmIaIfnAAZRyAgdiAcAAwQAwBW-9EABlHg809.jpg", "文件3");

        // 1.创建服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        // 2.提交执行
        Future<Boolean> r1 = service.submit(thread1);
        Future<Boolean> r2 = service.submit(thread2);
        Future<Boolean> r3 = service.submit(thread3);
        // 3.获取结果
        Boolean res1 = r1.get();
        Boolean res2 = r2.get();
        Boolean res3 = r3.get();
        System.out.println(res1);
        System.out.println(res2);
        System.out.println(res3);
        // 4.关闭服务
        service.shutdown();


        /*
            pool-1-thread-3执行开启的另一个线程
            pool-1-thread-2执行开启的另一个线程
            pool-1-thread-1执行开启的另一个线程
            true
            true
            true
         */
    }
}
// 下载器    https://commons.apache.org/proper/commons-io/download_io.cgi
class WebDownloader2{
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
